[vb,excel]统计excel表单元格批注内容相同的数量,急!在线等

来源:百度知道 编辑:UC知道 时间:2024/09/21 02:37:22
一个网友给我写了这样的代码,
——————
Public Function fx(ByVal a1 As Range)
Sum = 0
For Each x In a1
If InStr(x.Comment.Text, "中国") > 0 Then Sum = Sum + 1
Next
fx = Sum
End Function

————
单元格插入
=fx(a1:a7)

没有答案

插入=fx(a1),才显示答案。

代码哪错了?

可能a1:a7之间存在没有批注的单元格,导致程序出错。可以试一下以下的程序

Function fx(ByVal a1 As Range)
On Error Resume Next
For Each c In a1
c.addcomment.Text "5"
Next
Sum = 0
For Each x In a1
If InStr(x.Comment.Text, "中国") > 0 Then Sum = Sum + 1
Next
For Each c In a1
If c.Comment.Text = "5" Then
c.ClearComments
End If
Next
fx = Sum
End Function

fx(a1)只有一个变量,但你调用时却是用了a1:a7七个变量

当你引用的区域中,有的单元格没有批注,你现在使用的代码会出错。当作如下修改,可避免出现这种状况:
Public Function fx(ByVal a1 As Range)
Sum = 0
For Each x In a1
If Not x.Comment Is Nothing Then
If InStr(x.Comment.Text, "中国") > 0 Then Sum = Sum + 1
End If
Next
fx = Sum
End Function